<?php

namespace app\search\controller;

use think\Controller;
use think\Exception;
use think\Log;

class BaseController extends Controller
{
    protected function _initialize()
    {
        if(session("userInfo")==""){
            if (input("get.code") != "") {
                //说明已经此次请求为微信服务端发送过来的
                $code = input("get.code");

                //存入session，共其他部分调用
                insertUserInfoInSession(['code'=>$code]);

                //根据code，获取access_token
                $urlTemp=config("wechat.getAccessTokenUrl");
                $url=sprintf($urlTemp,config("wechat.AppId"),config("wechat.AppSecret"),$code);
                $data=curl_get($url);

                if(isset($data['errcode'])){
                    //错误处理
                    Log::write($data['errmsg']);
                    //与微信交互，发生接口返回错误就要把session("userInfo")给清零，并跳转到首页，重新刷新页面，否则会出问题
                    session("userInfo",null);
                    $this->redirect("search/Index/index");
                    return ;
                }
                //插入信息
                insertUserInfoInSession(['access_token'=>$data['access_token'],"expires_in"=>$data['expires_in'],"refresh_token"=>$data['refresh_token']]);
                //处理用户信息，
                //最终的结果是：存在session("userInfo")，并且session("userInfo")['data']!="";
                $this->handleUserInfo($data);

            } 
            else {
                //发送请求
                Log::write("-------------code存在");
                $urlTemp = config("wechat.getCodeUrl");
                $url = sprintf($urlTemp, config("wechat.AppId"), getCurrentUrl());
                $this->redirect($url);
                die;
            }
        }
    }

    //处理用户信息
    public function handleUserInfo($data){
        $openid=$data['openid'];
        //查找该用户openid是否在user表中存在，如果存在，直接将数据表中的数据查询出来，存入session
        //如果不存在，发起请求获取用户详细信息，入库，存入session
        $isset=model("PyUser")->field("usr_id,usr_openid")->where("usr_openid","=",$openid)->find();
        $userInfo=[];
        if($isset){
            //插入用户信息
            $userInfo=$isset;
        }else{
            //发送请求，获取用户微信信息
            $userInfo=$this->getUserInfo($data);
        }
        //将用户信息存入session
        insertUserInfoInSession(['data'=>$userInfo]);
    }



    //获取用户信息，将新用户信息存入数据库中
    public function getUserInfo($data){
        //校验access_token是否失效
        $tempUrl=config("wechat.checkAccessTokenUrl");
        $url=sprintf($tempUrl,$data['access_token'],$data['openid']);
        $result=curl_get($url);
        if($result['errcode']!=0){
            //已失效,刷新access_token
            $access_token=$this->refreshAccessToken(session("userInfo")['refresh_token']);
            insertUserInfoInSession(['access_token'=>$access_token]);
            $data['access_token']=$access_token;
        }

        //根据access_token和openid获取用户详细信息
        $userDetail=$this->getUserDetail($data);

        //将信息插入用户表
        $userData=[
            "usr_openid"=>$userDetail['openid'],
            "usr_nickname"=>$userDetail['nickname'],
            "usr_sex"=>$userDetail['sex'],
            "usr_pic"=>$userDetail['headimgurl']
        ];
        try{
            model("PyUser")->insert($userData);
        }catch (Exception $e){
            Log::write("前台获取新用户信息，并插入数据库时出现异常".$e->getMessage());
            return false;
        }

        //将信息存入session中
        //根据openid将用户信息查询出来，不使用Db::getLastInsID()是为了防止出错，并发
        $newUserData=model("PyUser")->field('usr_id')
            ->where("usr_openid","=",$userData['usr_openid'])
            ->find();
        $usr_id=$newUserData['usr_id'];
        //返回用户信息
        return [
            "usr_openid"=>$userData['usr_openid'],
            "usr_id"=>$usr_id,
        ];
    }

    public function refreshAccessToken($refresh_token){
        $tempUrl=config("wechat.refreshAccessTokenUrl");
        $url=sprintf($tempUrl,config("wechat.AppId"),$refresh_token);
        $result=curl_get($url);
        //将有效的access_token存入session
        insertUserInfoInSession(['access_token'=>$result['access_token']]);
        return $result['access_token'];
    }

    public function getUserDetail($data){
        $access_token=$data['access_token'];
        $openid=$data['openid'];
        $tempUrl=config("wechat.getUserInfoUrl");
        $url=sprintf($tempUrl,$access_token,$openid);
        $result=curl_get($url);
        return $result;
    }

    //指定返回信息
    public function uniteResponse($result,$successMsg){
        if($result!=1){
            $this->error($result);
        }else{
            $this->success($successMsg);
        }
    }
}
